package com.walterweimod.auxiliary_attributes.event;

import com.walterweimod.auxiliary_attributes.attribute.ModAttributes;
import com.walterweimod.auxiliary_attributes.util.ModRandomUtils;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.damagesource.EntityDamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeMap;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.Objects;

import static com.walterweimod.auxiliary_attributes.Auxiliary_attributes.*;

@Mod(MODID)
@Mod.EventBusSubscriber
public class CriticalHitEvent {
    @SubscribeEvent
    public static void livingCriticalAttack(LivingHurtEvent livingHurtEvent){
        DamageSource source = livingHurtEvent.getSource();

        if (source instanceof EntityDamageSource) {
            Entity sourceEntity = source.getEntity();

            if (sourceEntity instanceof LivingEntity attacker) {
                AttributeMap attributeMap = attacker.getAttributes();
                AttributeInstance critical_hit_chance = attributeMap.getInstance(ModAttributes.CRITICAL_HIT_CHANCE.get());
                AttributeInstance critical_hit_damage = attributeMap.getInstance(ModAttributes.CRITICAL_HIT_DAMAGE.get());

                double critical_hit_chance_value = 0.0D;
                double critical_hit_damage_value = 0.0D;

                if (Objects.nonNull(critical_hit_chance)){
                    critical_hit_chance_value = critical_hit_chance.getValue();
                }

                if (Objects.nonNull(critical_hit_damage)){
                    critical_hit_damage_value = critical_hit_damage.getValue();
                }

                if (critical_hit_chance_value > 0.0D){
                    float base_amount = livingHurtEvent.getAmount();

                    getLogger().info("玩家目前暴击率：" + critical_hit_chance_value);
                    getLogger().info("玩家目前暴击伤害：" + critical_hit_damage_value);

                    livingHurtEvent.setAmount(ModRandomUtils.critical_hit_algorithm(((float) critical_hit_chance_value), ((float) critical_hit_damage_value), base_amount));
                }
            }
        }
    }
}
